package com.renrendoc.network.flow.util;

import org.apache.kafka.common.protocol.types.Field;

import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {
    public static String getSpider(String ua) {
        String[] strings = {
                "baiduspider",
                "googlebot",
                "sosospider",
                "360spider",
                "slurp",
                "yodaobot",
                "sogouspider",
                "msnbot",
                "bingbot",
                "haosouspider",
                "mediapartners-google",
                "yahoo! slurp",
                "iaskspider",
                "sogou web spider",
                "sogou push spider",
                "bingpreview",
                "yisouspider",
                "bytespider"
        };

        if (null == ua) {
            ua = "n";
        }
        for (String string : strings) {
            if (ua.toLowerCase().contains(string)) {
                return string;
            }
        }

        return "n";
    }

    /**
     * 解析url 返回map k->v
     *
     * @param query
     * @return
     */
    public static Map<String, String> parseQueryString(String query) {
        Map<String, String> params = new HashMap<>();
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            try {
                String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
                String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
//                value = pair.substring(idx + 1);
//                if ("ru".equals(key)) {
//                    System.out.println(value);
//                }
                params.put(key, value);
            } catch (Exception e) {
                // Handle decoding exception
            }
        }
        return params;
    }

    /**
     * 解析nginx时间为timestamp
     * @param dateString
     * @return
     */
    public static Date convertToDate(String dateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        try {
            return dateFormat.parse(dateString);
        } catch (ParseException e) {
//            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析url中的文档id
     * @param input
     * @return
     */
    public static String extractNumber(String input) {
        // 匹配数字部分的正则表达式
        Pattern pattern = Pattern.compile("paper/(\\d+)");
        Matcher matcher = pattern.matcher(input);

        // 查找匹配的数字部分并返回
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }
}
